/**
 * Copyright &copy; 2015-2020 <a href="http://www.jeeplus.org/">JeePlus</a> All rights reserved.
 */
package com.jeeplus.modules.goods.service;

import java.math.BigDecimal;
import java.util.List;

import com.jeeplus.common.json.AjaxJson;
import com.jeeplus.common.utils.IdGen;
import com.jeeplus.common.utils.SnowFlake;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.account.entity.Account;
import com.jeeplus.modules.account.mapper.AccountMapper;
import com.jeeplus.modules.member.entity.Member;
import com.jeeplus.modules.member.mapper.MemberMapper;
import com.jeeplus.modules.orderbalance.entity.OrderBalance;
import com.jeeplus.modules.orderbalance.mapper.OrderBalanceMapper;
import com.jeeplus.modules.orders.entity.Orders;
import com.jeeplus.modules.orders.mapper.OrdersMapper;
import com.jeeplus.modules.recharge.entity.Recharge;
import com.jeeplus.modules.trade.entity.Trade;
import com.jeeplus.modules.trade.mapper.TradeMapper;
import com.jeeplus.modules.trades.entity.Trades;
import com.jeeplus.modules.trades.mapper.TradesMapper;
import com.jeeplus.modules.userbank.entity.Userbank;
import com.jeeplus.modules.userbank.mapper.UserbankMapper;
import com.jeeplus.modules.userpay.entity.Userpay;
import com.jeeplus.modules.userwx.entity.Userwx;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.jeeplus.core.persistence.Page;
import com.jeeplus.core.service.CrudService;
import com.jeeplus.modules.goods.entity.Goods;
import com.jeeplus.modules.goods.mapper.GoodsMapper;

/**
 * 商品Service
 * @author freedom
 * @version 2020-09-26
 */
@Service
@Transactional(readOnly = true)
public class GoodsService extends CrudService<GoodsMapper, Goods> {
	@Autowired
	private MemberMapper memberMapper;
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private TradeMapper tradeMapper;
	@Autowired
	private TradesMapper tradesMapper;
	@Autowired
	private UserbankMapper userbankMapper;
	@Autowired
	private AccountMapper accountMapper;
	@Autowired
	private OrderBalanceMapper orderBalanceMapper;

	public Goods get(String id) {
		return super.get(id);
	}
	
	public List<Goods> findList(Goods goods) {
		return super.findList(goods);
	}

	public List<Goods> findGoodsList(Goods goods) {
		return mapper.findGoodsList(goods);
	}
	
	public Page<Goods> findPage(Page<Goods> page, Goods goods) {
		// 商品展示添加持有人
		dataRuleFilter(goods);
		goods.setPage(page);
		List<Goods> list = mapper.findGoodsList(goods);
//		for (Goods goods1 : list) {
//			if (StringUtils.isNotBlank(goods1.getOrders().getId())){
//				Orders orders = ordersMapper.get(goods1.getOrders().getId());
//				if (!"3".equals(orders.getOrdersStatus()) && !"4".equals(orders.getOrdersStatus())){
//					Member member = memberMapper.get(orders.getMember().getId());
//					goods1.setHostUser(member.getLoginName());
//				}else {
//					Member member = memberMapper.get(orders.getTomem().getId());
//					goods1.setHostUser(member.getLoginName());
//					if ("4".equals(orders.getOrdersStatus())){
//						goods1.setGoodsStatus("5");
//					}
//				}
//			}else {
//				Orders orders = new Orders();
//				orders.setGoods(goods1);
//				List<Orders> ordersList = ordersMapper.findList(orders);
//				if (ordersList.size()>0){
//					if (!"3".equals(ordersList.get(0).getOrdersStatus()) && !"4".equals(orders.getOrdersStatus())){
//						goods1.setHostUser("admin");
//					}else {
//						Member member = memberMapper.get(ordersList.get(0).getTomem().getId());
//						goods1.setHostUser(member.getLoginName());
//						if ("4".equals(orders.getOrdersStatus())){
//							goods1.setGoodsStatus("5");
//						}
//					}
//				}else {
//					goods1.setHostUser("admin");
//				}
//			}
//
//		}
		page.setList(list);
		return page;
//		return super.findPage(page, goods);
	}
	
	@Transactional(readOnly = false)
	public void save(Goods goods) {
		if (goods.getIsNewRecord()){
			goods.setFirstPrice(goods.getPrice());
			//todo 持有人
			goods.setHostUser("admin");
			super.save(goods);
			Member member = new Member();
			member.setLoginName("admin");
			List<Member> memberList = memberMapper.findList(member);
			//插入交易记录
			Trade trade = new Trade();
			trade.setId(IdGen.uuid());
			trade.setGoods(goods);
			trade.setMember(memberList.get(0));
			trade.setTradeStatus("0");
			trade.setPayType("0");
			trade.setIsNewRecord(true);
			trade.preInsert();
			tradeMapper.insert(trade);
			//插入交易记录
			Trades trades = new Trades();
			trades.setId(IdGen.uuid());
			trades.setGoods(goods);
			trades.setMember(memberList.get(0));
			trades.setTradeStatus("0");
			trades.setPayType("0");
			trades.setIsNewRecord(true);
			trades.preInsert();
			tradesMapper.insert(trades);
		}else {
			super.save(goods);
		}
	}

	@Transactional(readOnly = false)
	public void saveGoodsForInterface(Goods goods) {
		super.save(goods);
	}
	
	@Transactional(readOnly = false)
	public void delete(Goods goods) {
		super.delete(goods);
	}


	public Page<Goods> findPageForFront(Page<Goods> goodsPage, Goods goods) {
		return super.findPage(goodsPage, goods);
	}


	@Transactional(readOnly = false)
	public AjaxJson saveSplitGoods(Goods goods) {
		AjaxJson aj = new AjaxJson();
		BigDecimal goodsMoney = BigDecimal.valueOf(goods.getPrice());
		BigDecimal relMoney = BigDecimal.valueOf(goods.getSplitPrice()).multiply(BigDecimal.valueOf(goods.getSplitAmount()));
		//先把这个商品更新分裂价格
		goods.setPrice(goods.getSplitPrice());
		//根据售卖价格，更改分区
		if (goods.getSplitPrice()>0 && goods.getSplitPrice()<=800){
			goods.setGoodsType("0");
		}else if (goods.getSplitPrice()>800 && goods.getSplitPrice()<=1800){
			goods.setGoodsType("1");
		}else if (goods.getSplitPrice()>1800 && goods.getSplitPrice()<=3000){
			goods.setGoodsType("2");
		}
// else if (goods.getSplitPrice()>2000 && goods.getSplitPrice()<=3000){
//			goods.setGoodsType("3");
//		}else if (goods.getSplitPrice()>3000 && goods.getSplitPrice()<=5000){
//			goods.setGoodsType("4");
//		}else if (goods.getSplitPrice()>5000){
//			goods.setGoodsType("5");
//		}
		goods.preUpdate();
		super.save(goods);
		//查询相关订单并复制
		Orders orders = ordersMapper.get(goods.getOrders().getId());
		Integer splits = goods.getSplitAmount()-1;
		for (int i = 0; i < splits; i++) {
			String goodsId = IdGen.uuid();
			//生成新的商品  和此购买商品相同
			Goods goods1 = new Goods();
			goods1.setId(goodsId);

			//生成新出售订单
			SnowFlake snowFlake1 = new SnowFlake(2, 3);
			//生成订单编号
			Long orderFormNumber1 = snowFlake1.nextId();
			String orderId = IdGen.uuid();
			Orders gOrder = new Orders();
			gOrder.setId(orderId);

			Orders orders2 = new Orders();
			orders2.setId(orderId);
			orders2.setOrdersNo(orderFormNumber1.toString());
			//0 上架中
			orders2.setOrdersStatus("0");
			//出售人
			orders2.setMember(orders.getMember());
			//收款方式
			orders2.setPayType(orders.getPayType());
			Userbank userbank = new Userbank();
			userbank.setMember(orders.getMember());
			List<Userbank> userbankList = userbankMapper.findList(userbank);
			if (userbankList.size()>0){
				orders2.setAccountNo(userbankList.get(0).getBankno());
				orders2.setAccountName(userbankList.get(0).getName());
			}else {
				aj.setSuccess(false);
				aj.setMsg("该用户银行卡信息有误，请确认是否完善。");
				return aj;
			}
			//商品id
			orders2.setGoods(goods1);
			orders2.setIsSale("1");
			orders2.setIsNewRecord(true);
			orders2.preInsert();
			ordersMapper.insert(orders2);

			//获取商品
//			Goods goods2 = get(goodsId);
			//给商品更改状态并该购买价格
//			goods2.setGoodsStatus("1");
//			goods2.setPrice(500d);
//			goods2.setOrders(gOrder);
//			super.save(goods2);
			goods1.setName(goods.getName());
			goods1.setPrice(goods.getSplitPrice());
			goods1.setFirstPrice(goods.getSplitPrice());
			goods1.setGoodsStatus("1");
			goods1.setMainImgs(goods.getMainImgs());
			goods1.setPic(goods.getPic());
			goods1.setGoodsType(goods.getGoodsType());
			goods1.setImgs(goods.getImgs());
			goods1.setOrders(gOrder);
			//todo 持有人
			goods1.setHostUser(goods.getHostUser());
			goods1.setIsNewRecord(true);
			goods.preInsert();
			super.save(goods1);
			//插入新的商品交易记录
			Trade trade1 = new Trade();
			trade1.setId(IdGen.uuid());
			trade1.setOrderNo(orders2.getOrdersNo());
			trade1.setTradeStatus("0");
			trade1.setMember(orders.getMember());
			trade1.setGoods(goods1);
			trade1.setPayType(orders.getPayType());
			trade1.setIsNewRecord(true);
			trade1.preInsert();
			tradeMapper.insert(trade1);
			//插入新的商品交易记录
			Trades trades1 = new Trades();
			trades1.setId(IdGen.uuid());
			trades1.setOrderNo(orders2.getOrdersNo());
			trades1.setTradeStatus("0");
			trades1.setMember(orders.getMember());
			trades1.setGoods(goods1);
			trades1.setPayType(orders.getPayType());
			trades1.setIsNewRecord(true);
			trades1.preInsert();
			tradesMapper.insert(trades1);
		}
		if (goodsMoney.compareTo(relMoney) == 1){
			BigDecimal addMoney = goodsMoney.subtract(relMoney);
			Account account = new Account();
			account.setMember(orders.getMember());
			List<Account> accountList = accountMapper.findList(account);
			if (accountList.size()>0){
				BigDecimal yue = BigDecimal.valueOf(accountList.get(0).getYue());
				accountList.get(0).setYue(yue.add(addMoney).doubleValue());
				accountList.get(0).preUpdate();
				accountMapper.update(accountList.get(0));
				//记录分裂
				OrderBalance orderBalance = new OrderBalance();
				orderBalance.setId(IdGen.uuid());
				orderBalance.setUpBalance(yue.doubleValue());
				orderBalance.setBalanceFlag("3");
				orderBalance.setBackBalance(addMoney.doubleValue());
				orderBalance.setMoney(goodsMoney.doubleValue());
				orderBalance.setOrderNo(orders.getOrdersNo());
				orderBalance.setMember(orders.getMember());
				orderBalance.setIsNewRecord(true);
				orderBalance.preInsert();
				orderBalanceMapper.insert(orderBalance);
			}
		}
		aj.setSuccess(true);
		aj.setMsg("分裂成功！");
		return aj;
	}
}